package com.cxdr.awsips.analysis.processor;

import java.io.File;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.cxdr.awsips.analysis.bean.FileBakLog;
import com.cxdr.awsips.analysis.bean.FileInfo;
import com.cxdr.awsips.analysis.bean.FileType;
import com.cxdr.awsips.analysis.bean.WriteDBLog;
import com.cxdr.awsips.analysis.config.SystemConfig;
import com.cxdr.awsips.analysis.db.DBHelper;
import com.cxdr.awsips.analysis.logger.LogFactory;
import com.cxdr.awsips.analysis.pool.BaseQueue;

public class FileAnalysis extends BaseProcessor {
	private static Logger logger = LogFactory.makeNewLogger(FileAnalysis.class);
	public static final BaseQueue<FileInfo> QUEUE = new BaseQueue<FileInfo>();
	private Connection connection ;
	private String FILE_END = null;
	private String ERROR_PATH = null;
	private String BACK_PATH = null;
	public FileAnalysis() {
		try {
			init();
		} catch (Exception e) {
			logger.error("初始化错误",e);
			logger.error("FilePakAnalysis 停止");
			e.printStackTrace();
			finish();
		}
	}
	private void init() throws Exception{
		connection = DBHelper.getConnection();
		FILE_END = SystemConfig.get("str.file-last-line");
		if(StringUtils.isBlank(FILE_END)){
			throw new Exception("获取文件终止符错误");
		}
		ERROR_PATH = SystemConfig.get("path.error");
		if(StringUtils.isBlank(FILE_END)){
			throw new Exception("获取异常文件路径错误");
		}
		File errorDir = new File(ERROR_PATH);
		if(!errorDir.isDirectory()){
			errorDir.mkdirs();
		}
		BACK_PATH = SystemConfig.get("path.back");
		if(StringUtils.isBlank(FILE_END)){
			throw new Exception("获取备份文件路径错误");
		}
		File backDir = new File(BACK_PATH);
		if(!backDir.isDirectory()){
			backDir.mkdirs();
		}
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		logger.info("开始打包文件解析线程");
		while(!isFinish()){
			FileInfo fileInfo = QUEUE.take();
			if(fileInfo==null){
				continue;
			}
			try{
				logger.info("取到文件："+(fileInfo.getFile().getName()));
				WriteDBLog writeDBLog = new WriteDBLog(fileInfo.getFile().getName());
				writeDBLog.setBegin_time(new Date());
				connection.setAutoCommit(false);
				List<String> lines = FileUtils.readLines(fileInfo.getFile());
				FileType type = fileInfo.getFileType();
				int writeCnt = 0;
				int lineCnt = 0;
				StringBuffer recodeLine = new StringBuffer();
				for(String line:lines){
					if(line.equalsIgnoreCase(FILE_END)){
						break;
					}
					if(recodeLine.length()==0){
						recodeLine.append(line);
					}else{
						recodeLine.append(";").append(line);
					}
					lineCnt++;
					if(lineCnt>0&&StringUtils.endsWith(line, "=")){
						//调用入库
						try{
							logger.info("入库");
							logger.info(recodeLine.toString());
							if(linIn(fileInfo,recodeLine.toString())){
								writeCnt++;
							}
						}catch(SQLException sqle){
							logger.error("入库错误：",sqle);
						}
						recodeLine = new StringBuffer();
					}
				}
				logger.info(fileInfo.getFile().getName()+" 入库 ："+writeCnt);
				connection.commit();
				FileBakLog log = bakFile(fileInfo.getFile(),BACK_PATH);
				FileBakLogProccessor.QUEUE.add(log);
				writeDBLog.setEnd_time(new Date());
				writeDBLog.setWrite_count(writeCnt);
				WriteDBLogProccessor.QUEUE.add(writeDBLog);
			}catch (Exception e){
				logger.error("解析文件错误",e);
				FileBakLog log = bakFile(fileInfo.getFile(),ERROR_PATH);
				FileBakLogProccessor.QUEUE.add(log);
			}
		}
	}
	private FileBakLog bakFile(File file,String path){
		FileBakLog log = new FileBakLog(file.getName());
		log.setBack_path(path);
		File backFile = new File(path+File.separator+file.getName());
		logger.info("备份文件："+file.getName()+" 到："+backFile.getAbsolutePath());
		file.renameTo(backFile);
		return log;
	}
	private boolean linIn(FileInfo info,String record) throws SQLException{
		switch(info.getFileType()){
		case E:
			return libInE(info,record);
		case N:
			return libInN(info,record);
		case D:
			return libInD(info,record);
		case R:
			return libInR(info,record);
		case Z:
			return libInZ(info,record);
		case AZ:
			return libInAZ(info,record);
		}
		return false;
	}
	//气象要素报
	private boolean libInE(FileInfo info,String record){
		CallableStatement stmt = null;
		String callSql = "";
		if(info.isIs_update()){
			callSql = "{call O_AWS_FTM_update(?,?,?,?)}";
		}else{
			callSql = "{call O_AWS_FTM_ADD(?,?,?,?)}";
		}
		try {
			stmt = connection.prepareCall(callSql);
			stmt.registerOutParameter(3, Types.NUMERIC);
			stmt.registerOutParameter(4, Types.VARCHAR);
			stmt.setString(1, record);
			stmt.setString(2, info.getFile().getName());
			stmt.execute();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("地面数据文件入库错误");
			logger.error("fileName:"+info.getFile().getName());
			logger.error("record:"+record);
			logger.error("错误信息：", e);
			return false;
		}finally{
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//雨量报文
	private boolean libInN(FileInfo info,String record){
		CallableStatement stmt = null;
		String callSql = "";
		if(info.isIs_update()){
			callSql = "{call pro_yuliang_update(?,?,?,?)}";
		}else{
			callSql = "{call pro_yuliang_add(?,?,?,?)}";
		}
		try {
			stmt = connection.prepareCall(callSql);
			stmt.registerOutParameter(3, Types.NUMERIC);
			stmt.registerOutParameter(4, Types.VARCHAR);
			stmt.setString(1, record);
			stmt.setString(2, info.getFile().getName());
			stmt.execute();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("雨量文件入库错误");
			logger.error("fileName:"+info.getFile().getName());
			logger.error("record:"+record);
			logger.error("错误信息：", e);
			return false;
		}finally{
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//状态数据包
	private boolean libInZ(FileInfo info,String record){
		CallableStatement stmt = null;
		String callSql = "";
		if(info.isIs_update()){
			callSql = "{call pro_zhuangtai_update(?,?,?,?)}";
		}else{
			callSql = "{call pro_zhuangtai_add(?,?,?,?)}";
		}
		try {
			stmt = connection.prepareCall(callSql);
			stmt.registerOutParameter(3, Types.NUMERIC);
			stmt.registerOutParameter(4, Types.VARCHAR);
			stmt.setString(1, record);
			stmt.setString(2, info.getFile().getName());
			stmt.execute();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("状态数据文件入库错误");
			logger.error("fileName:"+info.getFile().getName());
			logger.error("record:"+record);
			logger.error("错误信息：", e);
			return false;
		}finally{
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//日数据包
	private boolean libInD(FileInfo info,String record){
		CallableStatement stmt = null;
		String callSql = "";
		if(info.isIs_update()){
			callSql = "{call pro_rsj_update(?,?,?,?)}";
		}else{
			callSql = "{call pro_rsj_add(?,?,?,?)}";
		}
		try {
			stmt = connection.prepareCall(callSql);
			stmt.registerOutParameter(3, Types.NUMERIC);
			stmt.registerOutParameter(4, Types.VARCHAR);
			stmt.setString(1, record);
			stmt.setString(2, info.getFile().getName());
			stmt.execute();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("日数据报文件入库错误");
			logger.error("fileName:"+info.getFile().getName());
			logger.error("record:"+record);
			logger.error("错误信息：", e);
			return false;
		}finally{
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//辐射报文
	private boolean libInR(FileInfo info,String record){
		CallableStatement stmt = null;
		String callSql = "";
		if(info.isIs_update()){
			callSql = "{call pro_fushe_update(?,?,?,?)}";
		}else{
			callSql = "{call pro_fushe_add(?,?,?,?)}";
		}
		try {
			stmt = connection.prepareCall(callSql);
			stmt.registerOutParameter(3, Types.NUMERIC);
			stmt.registerOutParameter(4, Types.VARCHAR);
			stmt.setString(1, record);
			stmt.setString(2, info.getFile().getName());
			stmt.execute();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("辐射数据文件入库错误");
			logger.error("fileName:"+info.getFile().getName());
			logger.error("record:"+record);
			logger.error("错误信息：", e);
			return false;
		}finally{
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	private boolean libInAZ(FileInfo info,String record){
		return true;
	}
	public static void main(String[] args) {
		FileType f = FileType.D;
		System.out.println(f.getRecordCnt());
	}
	
}
